<template>
  <div>
    <el-form :model="formData" label-width="100px">
      <el-form-item label="省份(直辖市)">
        <el-select
          v-model="formData.province"
          placeholder="请选择省份(直辖市)"
          @change="onProvinceChange"
        >
          <el-option
            v-for="item in provinces"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="城市" v-if="formData.province">
        <el-select
          v-model="formData.city"
          placeholder="请选择城市"
          @change="onCityChange"
        >
          <el-option
            v-for="item in cities"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="区县" v-if="formData.city">
        <el-select v-model="formData.district" placeholder="请选择区县">
          <el-option
            v-for="item in districts"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="详细地址">
        <el-input
          v-model="formData.addressDetail"
          placeholder="请输入详细地址"
        ></el-input>
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="formData.remark"
          placeholder="请输入备注信息"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="save()">保存</el-button>
        <el-button @click="back()">返回</el-button>
      </el-form-item>
    </el-form>
    <div v-show="false">{{ address }}</div>
  </div>
</template>

<script>
import areaJsonDate from "@/assets/data/area_format_object.json";
export default {
  name: "addressAdd",
  data() {
    return {
      formData: {
        province: "",
        city: "",
        district: "",
        addressDetail: "",
        userId: "",
        remark: "",
      },
      addressFinal: "",
      areaDate: areaJsonDate,
      provinces: [],
      cities: [],
      districts: [],
    };
  },
  created() {
    const userJson = window.sessionStorage.getItem("user");
    if (userJson) {
      const user = JSON.parse(userJson);
      this.formData.userId = user.id;
    }
    // 初始化省份数据
    this.provinces = Object.keys(this.areaDate).map((code) => ({
      value: code,
      label: this.areaDate[code].n,
    }));
  },
  computed: {
    address() {
      let provinceName = "";
      let cityName = "";
      let districtName = "";
      if (this.formData.province) {
        // 获取省份名称
        provinceName = this.areaDate[this.formData.province].n;
      }
      if (this.formData.city) {
        // 获取城市名称
        cityName =
          this.areaDate[this.formData.province].c[this.formData.city].n;
      }
      if (this.formData.district) {
        // 获取区县名称
        districtName =
          this.areaDate[this.formData.province].c[this.formData.city].c[
            this.formData.district
          ].n;
      }
      // 拼接地址
      let address = provinceName;
      // 检查省份和城市名称是否不同（如直辖市）
      if (provinceName != cityName) {
        address += cityName;
      }
      // 添加区县名称
      address += districtName;
      return address;
    },
  },
  methods: {
    back() {
      this.$router.push("/managerIndex/manageAddress");
    },
    onProvinceChange(provinceCode) {
      // 清空城市和区县选择
      this.formData.city = "";
      this.formData.district = "";
      console.log("选择的省份" + this.areaDate[this.formData.province].n);
      // 获取对应省份下的城市数据
      if (provinceCode && this.areaDate[provinceCode]) {
        const citiesData = this.areaDate[provinceCode].c || {};
        this.cities = Object.keys(citiesData).map((code) => ({
          value: code,
          label: citiesData[code].n,
        }));
      } else {
        this.cities = [];
      }
      this.districts = [];
    },

    onCityChange(cityCode) {
      // 清空区县选择
      this.formData.district = "";
      console.log(
        "选择的城市" +
          this.areaDate[this.formData.province].c[this.formData.city].n
      );
      // 获取对应城市下的区县数据
      const provinceCode = this.formData.province;
      if (
        cityCode &&
        provinceCode &&
        this.areaDate[provinceCode] &&
        this.areaDate[provinceCode].c[cityCode]
      ) {
        const districtsData = this.areaDate[provinceCode].c[cityCode].c || {};
        this.districts = Object.keys(districtsData).map((code) => ({
          value: code,
          label: districtsData[code].n,
        }));
      } else {
        this.districts = [];
      }
    },

    save() {
      if (
        this.formData.province == "" ||
        this.formData.city == "" ||
        this.formData.district == ""
      ) {
        alert("请选择省市区县信息");
        return;
      }
      if (this.formData.addressDetail == "") {
        alert("请填写具体地址信息");
        return;
      }
      this.$axios
        .post("/api/address/add", {
          address: this.address + this.formData.addressDetail,
          userId: this.formData.userId,
          remark: this.formData.remark,
        })
        .then((response) => {
          if (response.data.addStatus) {
            this.$message.success("添加成功");
            this.$router.push("/managerIndex/manageAddress");
          } else {
            this.$message.error("添加失败: " + response.data.message);
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
  },
};
</script>
